let express = require("express");
let uunewid = require("uuid");
let router = express.Router();
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_COLLABORATION_MESSAGE";
const ohana_instance = new ohana(tableName);

const { checkAuth } = require("../utils/utils");
let constants = require("../utils/constants");

router.get("/", function (req, res, next) {
    // #swagger.tags = ['协同消息']
    // #swagger.summary = '获取消息列表'
    // #swagger.description = '需要JWT Token根据USER ID获取所有消息'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /* #swagger.parameters['status'] = {
            description: "已读为true 未读为false。非必要",
            required: false,
          } */
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }

    let payload = {};
    if (!user.admin) {
        payload.USER_ID = user.user_id;
    }
    const { status } = req.query;
    if (status) {
        payload.STATUS = status;
    }
    getData(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.get("/count", function (req, res, next) {
    // #swagger.tags = ['协同消息']
    // #swagger.summary = '获得协同消息条目数量'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /* #swagger.parameters['status'] = {
        description: "已读为true 未读为false。非必要",
        required: false,
      } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }
    const payload = {
        USER_ID: user.user_id,
    };
    const { status } = req.query;
    if (status) {
        payload.STATUS = status;
    }
    countDataList(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

// router.get("/getByDay", function (req, res, next) {
//     // #swagger.tags = ['协同消息']
//     // #swagger.summary = '获取当天列表'
//     // #swagger.description = '需要JWT Token'
//     /* #swagger.parameters['TODAY'] = {
//       description: "格式为 2021-10-24",
//       required: true,
//     } */
//     /* #swagger.security = [{
//                  "JiangduJWT": []
//     }] */
//     const user = checkAuth(req.user, constants.BASICAUTH);

//     if (!user.authCheck) {
//         res.sendStatus(403);
//         return
//     }

//     let payload = {};
//     if (!user.admin) {
//         payload.USER_ID = user.user_id;
//     }
//     let { TODAY } = req.query;
//     if (TODAY) {
//         payload.TODAY = TODAY;
//     }else{
//         res.status(400).send({"message":"参数错误 需要TODAY"});
//         return;
//     }

//     getTodayData(payload)
//         .then((result) => {
//             res.send(result);
//         })
//         .catch((err) => {
//             log.error(err);
//         });
// });

async function getTodayData(payload) {
    let result = [];
    result = await ohana_instance.raw(
        "select * from " +
        tableName +
        " where (USER_ID = '" +
        payload.USER_ID +
        "' or USER_ID = 'all') and START_DATE <= '" +
        payload.TODAY +
        "' and END_DATE >= '" +
        payload.TODAY +
        "'"
    );
    return result;
}

async function countDataList(payload) {
    let result = [];
    let countResult = await ohana_instance.count(payload);
    result.push({
        type: "total",
        count: countResult[0]["COUNT(*)"],
    });
    return result;
}

router.post("/", function (req, res, next) {
    // #swagger.tags = ['协同消息']
    // #swagger.summary = '创建消息'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/comessage_add"
                          }  
                      },
                  }
          } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }
    let { data } = req.body;
    // data.USER_ID = user.user_id;
    data.STATUS = data.STATUS ? data.STATUS : false;
    insertData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.status(400).send({ message: "插入数据异常" });
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.put("/", function (req, res, next) {
    // #swagger.tags = ['协同消息']
    // #swagger.summary = '更新协同消息'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/comessage_update"
                          }  
                      },
                  }
          } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }
    let { data } = req.body;
    data.USER_ID = user.user_id;
    updateData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.delete("/", function (req, res, next) {
    // #swagger.tags = ['协同消息']
    // #swagger.summary = '删除协同消息'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/comessage_delete"
                          }  
                      },
                  }
          } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }
    const { data } = req.body;
    deleteData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getData(condition) {
    let result = [];
    result = await ohana_instance.find(condition);
    return result;
}

async function insertData(data) {
    data.COLLABORATION_MESSAGE_ID = uunewid.v4();
    let result = await ohana_instance.insert(data);
    return result;
}

async function updateData(data) {
    let result = await ohana_instance.update(
        {
            COLLABORATION_MESSAGE_ID: data.COLLABORATION_MESSAGE_ID,
        },
        data
    );
    return result;
}

async function deleteData(data) {
    let result = await ohana_instance.raw(
        'delete from "' +
        tableName +
        "\" where COLLABORATION_MESSAGE_ID = '" +
        data.COLLABORATION_MESSAGE_ID +
        "'"
    );
    return result;
}

module.exports = router;
